package com.pdd.zookeeper.config;

import lombok.Data;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.CountDownLatch;

/**
 * @author:liyangpeng
 * @date:2020/8/27 9:26
 */
@Configuration
@ConfigurationProperties(prefix = "zookeeper")
@Data
public class ZookeeperConfig {

    private String nodes;

    private int timeout;

    private CountDownLatch countDownLatch=new CountDownLatch(1);

    @Bean
    public ZooKeeper getZookeeper(){
        try {
            //线程等待
            ZooKeeper zooKeeper=new ZooKeeper(nodes, timeout, new Watcher() {
                @Override
                public void process(WatchedEvent watchedEvent) {
                    if(watchedEvent.getState()==Event.KeeperState.SyncConnected){
                        //连接成功
                        countDownLatch.countDown();
                    }
                }
            });
            countDownLatch.await();
            return zooKeeper;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
